import os
import base64
import logging
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from datetime import datetime

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class TicketGenerator:
    def __init__(self, db_manager, aes_key):
        self.db_manager = db_manager
        self.aes_key = aes_key.encode('utf-8')
        # 确保AES密钥为16字节（AES-128）
        self.aes_key = self.aes_key.ljust(16, b'\x00')[:16]
        
    def generate(self, prefix, count):
        """生成指定数量的票据并保存到数据库"""
        generated_tickets = []
        
        for i in range(count):
            # 生成随机16进制字符串（8个字符）
            random_hex = os.urandom(4).hex()
            # 构建票号和原始数据
            ticket_number = f"{prefix}{i}"
            ticket_predata = f"{prefix}{i}_{random_hex}"
            
            # AES加密
            try:
                cipher = AES.new(self.aes_key, AES.MODE_ECB)
                padded_data = pad(ticket_predata.encode('utf-8'), AES.block_size)
                encrypted_data = cipher.encrypt(padded_data)
                ticket_data = base64.b64encode(encrypted_data).decode('utf-8')
            except Exception as e:
                logger.error(f'加密失败: {str(e)}')
                raise
            
            # 插入数据库
            sql = "INSERT INTO tickets (ticket_number, ticket_data, entry_state) VALUES (%s, %s, 0)"
            if self.db_manager.execute_update(sql, (ticket_number, ticket_data)):
                generated_tickets.append(f"{ticket_number}: {ticket_data}")
                logger.info(f'生成票据: {ticket_number}')
            else:
                logger.error(f'票据 {ticket_number} 插入数据库失败')
                raise Exception(f'票据 {ticket_number} 插入数据库失败')
        
        return generated_tickets